<template>
  <div class="friend-container">
    <!-- 好友列表头部 -->
    <div class="friend-header">
      <div class="header-actions">
        <el-input v-model="searchKeyword" placeholder="搜索好友..." prefix-icon="Search" clearable size="small"
          class="search-input" />
        <el-button type="primary" size="small" @click="showAddFriendDialog">
          <el-icon>
            <Plus />
          </el-icon>
          添加好友
        </el-button>
      </div>

      <!-- 好友请求通知 -->
      <div v-if="pendingRequestsCount > 0" class="friend-requests-notice">
        <el-alert :title="`您有 ${pendingRequestsCount} 个待处理的好友请求`" type="info" show-icon :closable="false">
          <template #default>
            <el-button type="text" size="small" @click="showFriendRequests">
              查看详情
            </el-button>
          </template>
        </el-alert>
      </div>
    </div>

    <!-- 好友分组列表 -->
    <div class="friend-groups">
      <!-- 在线好友 -->
      <div class="friend-group">
        <div class="group-header" @click="toggleGroup('online')">
          <el-icon class="expand-icon" :class="{ 'expanded': expandedGroups.online }">
            <ArrowRight />
          </el-icon>
          <span class="group-name">在线好友</span>
          <span class="friend-count">({{ onlineFriends.length }})</span>
        </div>

        <div v-show="expandedGroups.online" class="group-content">
          <div v-for="friend in onlineFriends" :key="friend.id" class="friend-item"
            @contextmenu.prevent="showFriendContextMenu($event, friend)" @dblclick="startChat(friend)">
            <div class="friend-avatar">
              <el-avatar :size="40" :src="friend.avatar">
                {{ friend.nickname.charAt(0) }}
              </el-avatar>
              <div class="status-indicator" :class="friend.status === 1 ? 'online' : 'offline'" />
            </div>

            <div class="friend-info">
              <div class="friend-name">
                {{ friend.nickname }}
                <el-icon v-if="friend.isFavorite" class="favorite-icon">
                  <Star />
                </el-icon>
              </div>
              <div class="friend-signature">{{ friend.signature || '这个人很懒，什么都没留下' }}</div>
            </div>

            <div class="friend-actions">
              <el-button circle size="small" @click="startChat(friend)">
                <el-icon>
                  <ChatRound />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 其他分组 -->
      <div v-for="group in friendGroups.filter(g => g.id !== 'online')" :key="group.id" class="friend-group">
        <div class="group-header" @click="toggleGroup(group.id)">
          <el-icon class="expand-icon" :class="{ 'expanded': group.isExpanded }">
            <ArrowRight />
          </el-icon>
          <span class="group-name">{{ group.name }}</span>
          <span class="friend-count">({{ friendsByGroup[group.id]?.length || 0 }})</span>
        </div>

        <div v-show="group.isExpanded" class="group-content">
          <div v-for="friend in friendsByGroup[group.id]" :key="friend.id" class="friend-item"
            @contextmenu.prevent="showFriendContextMenu($event, friend)" @dblclick="startChat(friend)">
            <div class="friend-avatar">
              <el-avatar :size="40" :src="friend.avatar">
                {{ friend.nickname.charAt(0) }}
              </el-avatar>
              <div class="status-indicator" :class="friend.status === 1 ? 'online' : 'offline'" />
            </div>

            <div class="friend-info">
              <div class="friend-name">
                {{ friend.nickname }}
                <el-icon v-if="friend.isFavorite" class="favorite-icon">
                  <Star />
                </el-icon>
              </div>
              <div class="friend-signature">{{ friend.signature || '这个人很懒，什么都没留下' }}</div>
            </div>

            <div class="friend-actions">
              <el-button circle size="small" @click="startChat(friend)">
                <el-icon>
                  <ChatRound />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加好友对话框 -->
    <el-dialog v-model="addFriendDialogVisible" title="添加好友" width="400px" :before-close="handleCloseAddFriendDialog">
      <el-form :model="addFriendForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="addFriendForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="验证消息">
          <el-input v-model="addFriendForm.message" type="textarea" :rows="3" placeholder="请输入验证消息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addFriendDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendFriendRequest">发送请求</el-button>
      </template>
    </el-dialog>

    <!-- 好友请求列表对话框 -->
    <el-dialog v-model="friendRequestsDialogVisible" title="好友请求" width="500px">
      <div class="friend-requests-list">
        <div v-for="request in friendRequests" :key="request.id" class="request-item">
          <div class="request-user">
            <el-avatar :size="40" :src="request.fromAvatar">
              {{ request.fromNickname.charAt(0) }}
            </el-avatar>
            <div class="user-info">
              <div class="user-name">{{ request.fromNickname }}</div>
              <div class="request-message">{{ request.message }}</div>
              <div class="request-time">{{ formatTime(request.timestamp) }}</div>
            </div>
          </div>

          <div v-if="request.status === 'pending'" class="request-actions">
            <el-button size="small" @click="handleFriendRequest(request.id, 'reject')">
              拒绝
            </el-button>
            <el-button type="primary" size="small" @click="handleFriendRequest(request.id, 'accept')">
              同意
            </el-button>
          </div>

          <div v-else class="request-status">
            <el-tag :type="request.status === 'accepted' ? 'success' : 'info'">
              {{ request.status === 'accepted' ? '已同意' : '已拒绝' }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, ArrowRight, Star, ChatRound, Search
} from '@element-plus/icons-vue'
import { useFriendStore, type Friend } from '@/stores/friend'
import { useChatStore } from '@/stores/chat'

const router = useRouter()
const friendStore = useFriendStore()
const chatStore = useChatStore()

// 响应式数据
const searchKeyword = ref('')
const addFriendDialogVisible = ref(false)
const friendRequestsDialogVisible = ref(false)
const expandedGroups = reactive({
  online: true
})

// 添加好友表单
const addFriendForm = reactive({
  username: '',
  message: '你好，我们可以成为好友吗？'
})

// 计算属性
const friendGroups = computed(() => friendStore.friendGroups)
const friendsByGroup = computed(() => friendStore.friendsByGroup)
const onlineFriends = computed(() => friendStore.onlineFriends)
const friendRequests = computed(() => friendStore.friendRequests)
const pendingRequestsCount = computed(() => friendStore.pendingRequestsCount)

// 切换分组展开状态
const toggleGroup = (groupId: string) => {
  if (groupId === 'online') {
    expandedGroups.online = !expandedGroups.online
  } else {
    friendStore.toggleGroupExpanded(groupId)
  }
}

// 显示添加好友对话框
const showAddFriendDialog = () => {
  addFriendDialogVisible.value = true
}

// 关闭添加好友对话框
const handleCloseAddFriendDialog = () => {
  addFriendDialogVisible.value = false
  addFriendForm.username = ''
  addFriendForm.message = '你好，我们可以成为好友吗？'
}

// 发送好友请求
const sendFriendRequest = () => {
  if (!addFriendForm.username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  friendStore.sendFriendRequest(addFriendForm.username, addFriendForm.message)
  ElMessage.success('好友请求已发送')
  handleCloseAddFriendDialog()
}

// 显示好友请求列表
const showFriendRequests = () => {
  friendRequestsDialogVisible.value = true
}

// 处理好友请求
const handleFriendRequest = (requestId: string, action: 'accept' | 'reject') => {
  const success = friendStore.handleFriendRequest(requestId, action)
  if (success) {
    ElMessage.success(action === 'accept' ? '已同意好友请求' : '已拒绝好友请求')
  }
}

// 开始聊天
const startChat = (friend: Friend) => {
  // 创建或获取会话
  const conversationId = `current-user-${friend.id}`.split('-').sort().join('-')

  // 添加或更新会话
  chatStore.addOrUpdateConversation({
    id: conversationId,
    participantId: friend.id,
    participantName: friend.nickname,
    participantAvatar: friend.avatar,
    unreadCount: 0,
    isOnline: friend.status === 'online',
    lastSeen: friend.lastSeen
  })

  // 跳转到聊天页面
  router.push('/chat')

  // 设置活跃会话
  setTimeout(() => {
    chatStore.setActiveConversation(conversationId)
  }, 100)
}

// 显示好友右键菜单
const showFriendContextMenu = (event: MouseEvent, friend: Friend) => {
  // 这里可以实现右键菜单功能
  console.log('右键菜单', friend)
}

// 格式化时间
const formatTime = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`

  return date.toLocaleDateString()
}

// 组件挂载时初始化数据
onMounted(() => {
  friendStore.initMockData()
})
</script>

<style scoped lang="scss">
.friend-container {
  height: 100vh;
  background: var(--bg-secondary);
  display: flex;
  flex-direction: column;
}

.friend-header {
  background: var(--bg-primary);
  padding: var(--spacing-md) var(--spacing-lg);
  border-bottom: 1px solid var(--border-light);
  box-shadow: var(--shadow-sm);

  .header-actions {
    display: flex;
    gap: var(--spacing-sm);
    align-items: center;

    .search-input {
      flex: 1;
      max-width: 300px;

      :deep(.el-input__wrapper) {
        border-radius: var(--radius-full);
        background: var(--bg-secondary);
        border: 1px solid var(--border-light);
        box-shadow: var(--shadow-sm);
        transition: var(--transition-fast);

        &:hover {
          background: var(--bg-tertiary);
          border-color: var(--border-medium);
        }

        &.is-focus {
          background: var(--bg-primary);
          border-color: var(--primary-500);
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
      }
    }

    .el-button {
      background: linear-gradient(135deg, var(--primary-500) 0%, var(--primary-600) 100%);
      border: none;
      color: var(--text-inverse);
      font-weight: var(--font-semibold);
      box-shadow: var(--shadow-sm);

      &:hover {
        transform: translateY(-1px);
        box-shadow: var(--shadow-md);
      }
    }
  }

  .friend-requests-notice {
    margin-top: var(--spacing-sm);
  }
}

.friend-groups {
  flex: 1;
  overflow-y: auto;
  background: white;

  .friend-group {
    border-bottom: 1px solid #f0f2f5;

    .group-header {
      display: flex;
      align-items: center;
      padding: 12px 20px;
      cursor: pointer;
      background: #fafbfc;
      transition: background-color 0.2s ease;

      &:hover {
        background: #f0f2f5;
      }

      .expand-icon {
        margin-right: 8px;
        transition: transform 0.2s ease;
        color: #8c8c8c;

        &.expanded {
          transform: rotate(90deg);
        }
      }

      .group-name {
        font-weight: 500;
        color: #262626;
        font-size: 14px;
      }

      .friend-count {
        margin-left: 4px;
        color: #8c8c8c;
        font-size: 12px;
      }
    }

    .group-content {
      .friend-item {
        display: flex;
        align-items: center;
        padding: 12px 20px 12px 40px;
        cursor: pointer;
        transition: background-color 0.2s ease;
        border-bottom: 1px solid #f8f9fa;

        &:hover {
          background: #f5f7fa;

          .friend-actions {
            opacity: 1;
          }
        }

        .friend-avatar {
          position: relative;
          margin-right: 12px;

          .status-indicator {
            position: absolute;
            bottom: 2px;
            right: 2px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            border: 2px solid white;

            &.online {
              background: #52c41a;
            }

            &.offline {
              background: #d9d9d9;
            }
          }
        }

        .friend-info {
          flex: 1;
          min-width: 0;

          .friend-name {
            display: flex;
            align-items: center;
            font-weight: 500;
            color: #262626;
            font-size: 14px;
            margin-bottom: 4px;

            .favorite-icon {
              margin-left: 4px;
              color: #faad14;
              font-size: 12px;
            }
          }

          .friend-signature {
            font-size: 12px;
            color: #8c8c8c;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .friend-actions {
          opacity: 0;
          transition: opacity 0.2s ease;
        }
      }
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #e4e7ed;
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.friend-requests-list {
  .request-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 0;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
    }

    .request-user {
      display: flex;
      align-items: center;
      flex: 1;

      .user-info {
        margin-left: 12px;

        .user-name {
          font-weight: 500;
          color: #262626;
          font-size: 14px;
          margin-bottom: 4px;
        }

        .request-message {
          font-size: 13px;
          color: #595959;
          margin-bottom: 4px;
          line-height: 1.4;
        }

        .request-time {
          font-size: 12px;
          color: #8c8c8c;
        }
      }
    }

    .request-actions {
      display: flex;
      gap: 8px;
    }

    .request-status {
      margin-left: 12px;
    }
  }
}
</style>
